<template>
  <div class="vm">
    <h2 class="h-title">广州图层显示</h2>
    <div ref="map" class="map-x"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import { Style, Text, Stroke, Fill } from "ol/style";
import GEOJSON_CONST from "../../assets/data/guangZhou.json";
export default {
  data() {
    return {
      map: null, // 地图
    };
  },
  methods: {
    getLayer() {
      //用GeoJSON().readFeatures读取GEOJSON_CONST并遍历处理格式
      const result = new GeoJSON().readFeatures(GEOJSON_CONST);
      result.forEach((item) => {
        const style = new Style({
          text: new Text({
            text: item.values_.name,
            font: "normal 18px 黑体",
            textAlign: "center",
            fill: new Fill({
              color: "black",
            }),
          }),
          stroke: new Stroke({
            color: "green",
            width: 5,
          }),
          fill: new Fill({
            color: "rgba(255, 255, 0, 0.5)",
          }),
        });
        item.setStyle(style);
      });
      let source = new SourceVector({
        // 2.处理后的geojson扔进SourceVector的features
        features: result,
      });

      this.geoLayer = new LayerVector({
        //3.source扔进LayerVector的source
        source: source,
      });
      //4.添加LayerVector图层
      this.map.addLayer(this.geoLayer);
      // 5.设置倾斜角度
      const view = this.map.getView();
      view.setZoom(9);
    },
    initMap() {
      let raster = new Tile({
        source: new OSM(),
      });
      this.map = new Map({
        target: this.$refs.map,
        layers: [raster],
        view: new View({
          projection: "EPSG:4326",
          center: [113.1206, 23.034996],
          zoom: 10,
        }),
      });
    },
  },
  mounted() {
    this.initMap();
    this.getLayer();
  },
};
</script>

<style>
</style>